package com.huanletao.quartz.schedule;

import com.huanletao.quartz.entity.JobDetails;
import com.huanletao.quartz.execute.ExecuteJobQuartz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * description: DbUtils <br>
 * date: 2022/7/4 16:51 <br>
 * author: 踏雪无痕 <br>
 * version: 1.0 <br>
 */
public abstract class QuartzDataManager {

    private static final Logger logger = LoggerFactory.getLogger(QuartzDataManager.class);

    protected DataSource dataSource;

    public QuartzDataManager(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @SuppressWarnings("all")
    public boolean getJobExecuteFlag(JobDetails details) throws Exception {
        Connection conn = getConnection();
        conn.setAutoCommit(false);
        boolean flag = false;
        String sql = "SELECT status FROM job_info where id =? for update ";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setLong(1, details.getId());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                String status = rs.getString("status");
                if ("1".equals(status)) {
                    PreparedStatement preparedStatement = conn.prepareStatement("update job_info set status = 2 where id =?");
                    preparedStatement.setLong(1, details.getId());
                    int num = preparedStatement.executeUpdate();
                    if (num >= 1) {
                        logger.info("执行修改执行状态为正在执行，job_name={}", details.getJobName());
                        flag = true;
                    }
                    preparedStatement.close();
                }
            }
            ps.close();
            conn.commit();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @SuppressWarnings("all")
    public boolean resumeExecuteFlag(JobDetails details) throws Exception {
        Connection conn = getConnection();
        conn.setAutoCommit(false);
        boolean flag = false;
        try {
            PreparedStatement ps = conn.prepareStatement("update job_info set status = 1 where id=?");
            ps.setLong(1, details.getId());
            int n = ps.executeUpdate();
            if (n >= 1) {
                flag = true;
                logger.info("状态还原成功，job_name={}", details.getJobName());
            }
            ps.close();
            conn.commit();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @SuppressWarnings("all")
    public List<JobDetails> selectRunJobs() {
        Connection conn = getConnection();
        List<JobDetails> detailsList = new ArrayList<>();
        try {
            String sql = "select id,job_name,group_name,cron,invoke_target,status,misfire_policy from job_info where status = 1";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                long id = rs.getLong("id");
                String jobName = rs.getString("job_name");
                String groupName = rs.getString("group_name");
                String cron = rs.getString("cron");
                String targetName = rs.getString("invoke_target");
                String status = rs.getString("status");
                int misfirePolicy = rs.getInt("misfire_policy");
                JobDetails jobDetails = new JobDetails(jobName, groupName, cron, targetName,status);
                jobDetails.setId(id);
                jobDetails.setMisfirePolicy(misfirePolicy);
                jobDetails.setExecuteJobClass(ExecuteJobQuartz.class);
                logger.info("查询到的定时任务：{}",jobDetails);
                detailsList.add(jobDetails);
            }
            ps.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detailsList;
    }

    private Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
